package com.zbbt.sportslottery.ui.fragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.gc.materialdesign.views.ProgressBarCircularIndetermininate;
import com.google.gson.JsonObject;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zbbt.sportslottery.R;
import com.zbbt.sportslottery.app.App;
import com.zbbt.sportslottery.app.Constant;
import com.zbbt.sportslottery.app.ServerConfig;
import com.zbbt.sportslottery.bean.BallDataBean;
import com.zbbt.sportslottery.bean.DialogBean.OnDialogClickListener;
import com.zbbt.sportslottery.bean.FocusData;
import com.zbbt.sportslottery.bean.IndexFunBean;
import com.zbbt.sportslottery.bean.News;
import com.zbbt.sportslottery.bean.NewsProgarm;
import com.zbbt.sportslottery.bean.SuperResult;
import com.zbbt.sportslottery.db.DbManager;
import com.zbbt.sportslottery.net.TypeGsonHttpHandler;
import com.zbbt.sportslottery.net.ZbHttpClient;
import com.zbbt.sportslottery.ui.activity.ActionInfoActivity;
import com.zbbt.sportslottery.ui.activity.DrawNoticeActivity;
import com.zbbt.sportslottery.ui.activity.ElevenWebViewActivity;
import com.zbbt.sportslottery.ui.activity.GameDataActivity;
import com.zbbt.sportslottery.ui.activity.LotteryShopActivity;
import com.zbbt.sportslottery.ui.activity.MainActivity;
import com.zbbt.sportslottery.ui.adapter.GridViewAdapter;
import com.zbbt.sportslottery.ui.adapter.RecyclerViewAdapter;
import com.zbbt.sportslottery.ui.widget.HeadRecyclerView;
import com.zbbt.sportslottery.ui.widget.recycler.MyItemClickListener;
import com.zbbt.sportslottery.ui.widget.swipe.SwipeRefreshLayout;
import com.zbbt.sportslottery.ui.widget.swipe.SwipeRefreshLayout.OnRefreshListener;
import com.zbbt.sportslottery.util.AppUtil;
import com.zbbt.sportslottery.util.DialogUtil;
import com.zbbt.sportslottery.util.KeyUtil;
import com.zbbt.sportslottery.util.LogUtil;
import com.zbbt.sportslottery.util.MoneyUtil;
import com.zbbt.sportslottery.util.ScreenUtil;
import com.zbbt.sportslottery.util.SharePreferUtil;
import com.zbbt.sportslottery.util.UmengUtil;

public class IndexFragment extends SimpleBaseFragment {
	private RecyclerView recyclerView;
	private SwipeRefreshLayout swipeRefreshLayout;
	private RecyclerViewAdapter adapter;
	private GridViewAdapter gridViewAdapter;
	private List<FocusData> focusDataList = new ArrayList<FocusData>();
	private List<News> homeListData = new ArrayList<News>();
	private List<View> pageViewsList = new ArrayList<View>();// 存放焦点图片
	private List<String> textsList = new ArrayList<String>();// 存放焦点文字描述
	private List<IndexFunBean> indexFunBeans = new ArrayList<IndexFunBean>();
	private int curPage = 1;
	private int pageSize = 5;// 读取本地缓存翻页 一页10条
	private int pageTotal = 1;// 读取本地缓存翻页 当前页数
	private LayoutInflater inflater;
	private int currentIndex;
	private boolean available = false;
	private final int NEXT_FOCUS = 2;// 更换图片的消息的标志
	private final int TEME = 5000;// 每张图片停留的时间
	private ViewHolder myholder;
	private LinearLayout llRight;
	private TextView ballview;
	private LinearLayout error_layout;
	private ProgressBarCircularIndetermininate indetermininate;
	private Intent loginSuccess;

	public IndexFragment() {}

	public static IndexFragment getInstance() {
		return new IndexFragment();
	}

	@Override
	protected void initView(LayoutInflater inflater) {
		this.inflater = inflater;
		mView = inflater.inflate(R.layout.fragment_index, null);
		loginSuccess = new Intent(Constant.INTENT_ACTION_CHANGE_CITY);
		findViewById();
	}

	private void findViewById() {
		error_layout = (LinearLayout) findViewById(R.id.error_layout);
		indetermininate = (ProgressBarCircularIndetermininate) findViewById(R.id.progressBarCircularIndetermininate);
		tv_right = (TextView) findViewById(R.id.tv_right);
		recyclerView = (RecyclerView) findViewById(R.id.recyc_listView);
		recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
		recyclerView.setItemAnimator(new DefaultItemAnimator());
		recyclerView.setHasFixedSize(false);
		swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.index_swipe_container);
		adapter = new RecyclerViewAdapter(homeListData, context);
		adapter.setOnBindHeadView(new RecyclerViewAdapter.HeaderRecyclerView() {
			@Override
			public void onBindHeaderView(ViewHolder holder, int position) {
				myholder = holder;
				getFocuseData();// 焦点
				getBallDataKj();// 开奖
				getFourBigPicList();// 获取4图片url
				getFourBigPicData();// 初始化功能区入口
			}
		});

		adapter.setOnBottomClickListener(new RecyclerViewAdapter.OnBottomClickListener() {
			@Override
			public void onButtomClick() {
				getHomeListData(Constant.REFRESH);

			}
		});
		recyclerView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
		adapter.setOnItemClickListener(onItemClickListener);
		swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				getHomeListData(Constant.REFRESH);
			}
		});
		getHomeListData(Constant.REFRESH);
		getProgarmList();// 获取新闻栏目
		if (App.PARAM_SDK_VERSION <= 10) {
			swipeRefreshLayout.setEnabled(false);
		}
	}

	/**
	 * 
	 * @MethodName:getBallDataKj
	 * @Description: 今日开奖
	 * @author：GaomingShuo
	 * @date：2015-4-2 下午5:37:20 void
	 */
	private void getBallDataKj() {
		JsonObject jsonObject = new JsonObject();
		ZbHttpClient.postNewApi(ServerConfig.API_DRAW_NOTICE, jsonObject,
				new TypeGsonHttpHandler<SuperResult<BallDataBean>>() {
					@Override
					public void onSuccess(SuperResult<BallDataBean> data) {
						if (data != null) {
							ArrayList<BallDataBean> kjdataList = data.getData();
							if (data.getData() != null && data.getData().size() > 0) {
								String jackpotBonus = kjdataList.get(0).getJackpotBonus();
								((HeadRecyclerView) myholder).kj_name.setText(kjdataList.get(0)
										.getLotteryName());
								((HeadRecyclerView) myholder).kj_data.setText("第"
										+ kjdataList.get(0).getDrawId() + "期");
								if (kjdataList.get(0).getLotteryCode().equals("3000")) {
									((HeadRecyclerView) myholder).kj_money.setText(jackpotBonus);
									((HeadRecyclerView) myholder).kj_text.setVisibility(View.GONE);
									((HeadRecyclerView) myholder).kj_money.setTextColor(context
											.getResources().getColor(R.color.black_54));
								} else {
									((HeadRecyclerView) myholder).kj_text.setVisibility(View.VISIBLE);
									((HeadRecyclerView) myholder).kj_money.setText(MoneyUtil
											.getMoneyChangeString(jackpotBonus));
									((HeadRecyclerView) myholder).kj_money.setTextColor(context
											.getResources().getColor(R.color.red_new));
								}
								String number = kjdataList.get(0).getResult();
								String bullber = kjdataList.get(0).getAddResult();
								((HeadRecyclerView) myholder).ball_layout.removeAllViews();
								LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
										LinearLayout.LayoutParams.WRAP_CONTENT,
										LinearLayout.LayoutParams.WRAP_CONTENT);
								layoutParams.setMargins(6, 5, 6, 5);
								if (!TextUtils.isEmpty(number)) {
									if (number.contains(",")) {
										String[] allString = number.split(",");
										if (kjdataList.get(0).getLotteryCode().equals("4707")) {
											Arrays.sort(allString);
										}
										for (int i = 0; i < allString.length; i++) {
											ballview = (TextView) inflater.inflate(R.layout.item_ball_list,
													null);
											ballview.setLayoutParams(layoutParams);
											ballview.setText(allString[i]);
											ballview.setPadding(5, 5, 5, 5);
											ballview.setBackgroundResource(R.drawable.redball);
											((HeadRecyclerView) myholder).ball_layout.addView(ballview);
										}

									}
								}
								if (!TextUtils.isEmpty(bullber) && !bullber.equals("null")) {
									String[] bullStrings = bullber.split(",");
									if (kjdataList.get(0).getLotteryCode().equals("4707")) {
										Arrays.sort(bullStrings);
									}
									for (int i = 0; i < bullStrings.length; i++) {
										ballview = (TextView) inflater.inflate(R.layout.item_ball_list, null);
										ballview.setLayoutParams(layoutParams);
										ballview.setText(bullStrings[i]);
										ballview.setPadding(5, 5, 5, 5);
										ballview.setBackgroundResource(R.drawable.blueball);
										((HeadRecyclerView) myholder).ball_layout.addView(ballview);
									}
								}
								((HeadRecyclerView) myholder).kj_gonggao
										.setOnClickListener(new OnClickListener() {

											@Override
											public void onClick(View v) {
												UmengUtil.onEvent(context, Constant.UMENG_HOME_OPEN);
												goActivity(DrawNoticeActivity.class);
											}
										});
							}

						}

					}

					@Override
					public void onFailure(String errorCode, String errorMsg) {

					}
				});
	}

	/**
	 * @MethodName:onResume
	 * @Description: 获取开奖中的四个板块
	 * @author：GaomingShuo
	 * @date：2015-4-2 上午10:36:05 void
	 */

	private void getFourBigPicData() {
		if (gridViewAdapter == null) {
			gridViewAdapter = new GridViewAdapter(context, indexFunBeans);
			((HeadRecyclerView) myholder).gridView.setAdapter(gridViewAdapter);
			gridViewAdapter.notifyDataSetChanged();
			((HeadRecyclerView) myholder).gridView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					Constant.HREURL = indexFunBeans.get(position).getHrefUrl();
					Constant.REMARK = indexFunBeans.get(position).getRemark();
					switch (position) {
					case 0:// 11选5
						Constant.isEvlenIsopen = indexFunBeans.get(position).getIsOpen();
						UmengUtil.onEvent(context, Constant.UMENG_HOME_CHART);
						Intent intentE = new Intent(context, ElevenWebViewActivity.class);
						intentE.putExtra("isOpen", Constant.isEvlenIsopen);
						intentE.putExtra("evelentUrl", Constant.HREURL);
						intentE.putExtra("evelname", Constant.REMARK);
						startActivity(intentE);
						break;
					case 1:// 网点儿
						Constant.isShopIsopen=indexFunBeans.get(position).getIsOpen();
						UmengUtil.onEvent(context, Constant.UMENG_HOME_MAP);
						Intent intentL = new Intent(context, LotteryShopActivity.class);
						intentL.putExtra("isOpen", Constant.isShopIsopen);
						startActivity(intentL);
						break;
					case 2:// 赛事数据 无数据
						UmengUtil.onEvent(context, Constant.UMENG_HOME_MATCH);
						String hrefUrl = indexFunBeans.get(position).getHrefUrl();
						Intent intent1 = new Intent(context, GameDataActivity.class);
						intent1.putExtra("Title", "赛事数据");
						intent1.putExtra("ShowShare", false);
						intent1.putExtra("Url", hrefUrl);
						intent1.putExtra("isOpen", Constant.isEvlenIsopen);
						intent1.putExtra("ShowImg", false);
						startActivity(intent1);
						break;
					case 3:// 活动中心 无数据
						UmengUtil.onEvent(context, Constant.UMENG_HOME_ACTIVITY);
						String url = indexFunBeans.get(position).getHrefUrl();
//						if (TextUtils.isEmpty(url) || url.equals("null")) {
							((MainActivity) getActivity()).changeFragment(KeyUtil.FRAG_ACTION);
//						} else {
//							Intent intent = new Intent(context, ActionInfoActivity.class);
//							intent.putExtra("isOpen", Constant.isEvlenIsopen);
//							intent.putExtra("Url", url);
//							intent.putExtra("Title", "活动");
//							intent.putExtra("ShowShare", true);
//							if (indexFunBeans.get(position).getHrefUrl() != null) {
//								intent.putExtra("ImageUrl", indexFunBeans.get(position).getHrefUrl());
//							}
//							intent.putExtra("ShareTitle", indexFunBeans.get(position).getFunDesSecond());
//							intent.putExtra("SummaryTx", indexFunBeans.get(position).getRemark());
//							startActivity(intent);
//						}
						break;

					default:
						break;
					}
				}
			});
		}
		gridViewAdapter.notifyDataSetChanged();
	}

	/**
	 * @MethodName:getFourBigPicList
	 * @Description: 功能入口数据
	 * @author：GaomingShuo
	 * @date：2015-4-3 下午4:24:37 void
	 */
	private void getFourBigPicList() {
		JsonObject jsonObject = new JsonObject();
		String pARAM_APPID = App.PARAM_APPID;
		LogUtil.printD("pARAM_APPID", pARAM_APPID);
		ZbHttpClient.postNewApi(ServerConfig.API_DRAW_FOUR, jsonObject,
				new TypeGsonHttpHandler<List<IndexFunBean>>() {

					@Override
					public void onSuccess(List<IndexFunBean> data) {
						if (data != null) {
							indexFunBeans.clear();
							indexFunBeans.addAll(data);
							gridViewAdapter.notifyDataSetChanged();
							for (int i = 0; i < indexFunBeans.size(); i++) {
								Constant.HREURL = indexFunBeans.get(0).getHrefUrl();
								Constant.REMARK = indexFunBeans.get(0).getRemark();
								if(i==1){
									Constant.isShopIsopen=indexFunBeans.get(1).getIsOpen();
								}else{
									Constant.isEvlenIsopen = indexFunBeans.get(0).getIsOpen();
								}
							}
						} else {
							indexFunBeans.clear();
							gridViewAdapter.notifyDataSetChanged();
						}
						gridViewAdapter.notifyDataSetChanged();

					}

					@Override
					public void onFailure(String errorCode, String errorMsg) {}
				});
	}

	@Override
	public void onResume() {
		super.onResume();
		available = true;
		handler.sendEmptyMessageDelayed(NEXT_FOCUS, TEME);// 给handler发送一个延时更换消息
		String cityName = SharePreferUtil.getString(Constant.CITY_NAME, "");
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		} else {
			adapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		available = false;
	}

	/**
	 * 
	 * @MethodName:getFocuseData
	 * @Description: 获取焦点数据
	 * @author：GaomingShuo
	 * @date：2015-4-1 下午2:44:13 void
	 */
	private void getFocuseData() {

		JsonObject jsonObject = new JsonObject();
		ZbHttpClient.postNewApi(ServerConfig.API_NEWS_FOCUS_LIST, jsonObject,
				new TypeGsonHttpHandler<List<FocusData>>() {

					@Override
					public void onSuccess(List<FocusData> data) {
						if (data != null) {
							focusDataList.clear();
							focusDataList.addAll(data);
							((HeadRecyclerView) myholder).text_point_ll.setVisibility(View.VISIBLE);
							recyclerView.setBackgroundResource(R.color.gray_bg);
						}
						focusDataInit();
						DbManager.savefoucelist(focusDataList);
						pageAdapter.notifyDataSetChanged();
					}

					@Override
					public void onFailure(String errorCode, String errorMsg) {
						getFocuseLocalList();
					}
				});
	}

	/**
	 * 获取焦点新闻本地缓存数据
	 */
	public void getFocuseLocalList() {
		List<FocusData> focuslistdata = DbManager.getFouceList();
		if (focuslistdata != null) {
			if (focusDataList != null) {
				focusDataList.clear();
			} else {
				focusDataList = new ArrayList<FocusData>();
			}
			focusDataList.addAll(focuslistdata);
			pageAdapter.notifyDataSetChanged();
			// error_linear.setVisibility(View.GONE);
		} else {
			// error_linear.setVisibility(View.VISIBLE);
		}
	}

	/*****
	 * 初始化焦点数据
	 */
	void focusDataInit() {
		try {
			View fv = null;
			pageViewsList.clear();
			textsList.clear();

			for (int i = focusDataList.size() - 1; i >= 0; i--) {
				final int countnum = i;
				fv = inflater.inflate(R.layout.page_4_focus_view, null);
				ImageView focusImage = ((ImageView) fv.findViewById(R.id.img_4_focus));
				if (null != focusDataList.get(i).getImgUrl() && !focusDataList.get(i).getImgUrl().equals(""))
					ImageLoader.getInstance().displayImage(focusDataList.get(i).getImgUrl() + "", focusImage,
							App.option);
				focusImage.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						UmengUtil.onEvent(context, Constant.UMENG_HOME_JDT);
						Intent intent = new Intent(getActivity(), GameDataActivity.class);
						intent.putExtra("Url", focusDataList.get(countnum).getDetialUrl());
						intent.putExtra("Title", "热点");
						intent.putExtra("ShowShare", true);
						intent.putExtra("ImageUrl", focusDataList.get(countnum).getImgUrl());
						intent.putExtra("ShareTitle", focusDataList.get(countnum).getTitle());
						getActivity().startActivity(intent);
					}
				});
				textsList.add(0, focusDataList.get(i).getTitle());
				pageViewsList.add(0, fv);
			}
			((HeadRecyclerView) myholder).view_pager_4_focus.setAdapter(pageAdapter);
			ImageView point;// 点 对象
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT, 1); // 点
			// 参数
			params.setMargins(0, 0, 5, 0);

			// 添加 点 到界面
			((HeadRecyclerView) myholder).pointLayout.removeAllViews();
			for (int i = 0; i < focusDataList.size(); i++) {
				point = new ImageView(getActivity());
				point.setBackgroundResource(R.drawable.selector_point);
				point.setEnabled(false);
				point.setLayoutParams(params);
				((HeadRecyclerView) myholder).pointLayout.addView(point);
			}

			// 设置第一次显示情况
			// 下面（1000）表示可以向右滑动大约一千次，本来应该用Integer.Max_Value/2,但是数据到十亿级别是有些手机会崩溃，这里设置成一千
			currentIndex = 1000 - 1000 % pageViewsList.size();

			if (pageViewsList.size() > 1) {
				((HeadRecyclerView) myholder).view_pager_4_focus.setCurrentItem(currentIndex);
				((HeadRecyclerView) myholder).text4Focus.setText(textsList.get(currentIndex
						% pageViewsList.size()));
				((HeadRecyclerView) myholder).pointLayout.getChildAt(currentIndex % pageViewsList.size())
						.setEnabled(true);
			} else {
				((HeadRecyclerView) myholder).text4Focus.setText(textsList.get(0));
				((HeadRecyclerView) myholder).pointLayout.getChildAt(0).setEnabled(true);
			}
			// 选中页改变
			((HeadRecyclerView) myholder).view_pager_4_focus
					.setOnPageChangeListener(new OnPageChangeListener() {

						@Override
						public void onPageSelected(int location) {
							// 设置 点
							((HeadRecyclerView) myholder).pointLayout.getChildAt(
									currentIndex % pageViewsList.size()).setEnabled(false);
							((HeadRecyclerView) myholder).pointLayout.getChildAt(
									location % pageViewsList.size()).setEnabled(true);
							currentIndex = location;
							// 设置描述
							((HeadRecyclerView) myholder).text4Focus.setText(textsList.get(location
									% pageViewsList.size()));
						}

						@Override
						public void onPageScrolled(int arg0, float arg1, int arg2) {
							LogUtil.defLog("arg0=" + arg0 + "arg1=" + arg1 + "arg2=" + arg2);
						}

						@Override
						public void onPageScrollStateChanged(int arg0) {
							// LogUtil.defLog("onPageScrollStateChanged="+arg0);
							if (arg0 == 1) {
								SwipeRefreshLayout.issetTou = false;
								handler.removeMessages(NEXT_FOCUS);
							} else if (arg0 == 0) {
								SwipeRefreshLayout.issetTou = true;
								handler.sendEmptyMessageDelayed(NEXT_FOCUS, TEME);
								swipeRefreshLayout.setFocusableInTouchMode(true);
							}

						}
					});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 异步信息处理器
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {

			if (available) {
				switch (msg.what) {
				case NEXT_FOCUS:
					if (pageViewsList.size() > 1) {
						((HeadRecyclerView) myholder).view_pager_4_focus
								.setCurrentItem(((HeadRecyclerView) myholder).view_pager_4_focus
										.getCurrentItem() + 1);
					}
					handler.removeMessages(NEXT_FOCUS);
					handler.sendEmptyMessageDelayed(NEXT_FOCUS, TEME);
					break;
				}
			}
		};
	};

	/**
	 * view pager适配器
	 */
	private PagerAdapter pageAdapter = new PagerAdapter() {

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public int getCount() {
			if (pageViewsList.size() > 1)
				return Integer.MAX_VALUE;
			else
				return pageViewsList.size();
		}

		@Override
		public void destroyItem(View container, int position, Object object) {}

		@Override
		public Object instantiateItem(View container, int position) {
			if (pageViewsList.get(position % pageViewsList.size()).getParent() != null) {
				((ViewPager) pageViewsList.get(position % pageViewsList.size()).getParent())
						.removeView(pageViewsList.get(position % pageViewsList.size()));
			}
			((ViewPager) container).addView(pageViewsList.get(position % pageViewsList.size()), 0);

			return pageViewsList.get(position % pageViewsList.size());
		}
	};

	@Override
	protected void setListener() {
		error_layout.setOnClickListener(this);
	}

	@Override
	protected void onClickEvent(View v) {
		switch (v.getId()) {
		
		case R.id.error_layout:
			getHomeListData(Constant.REFRESH);
			indetermininate.setVisibility(View.VISIBLE);
			break;
		default:
			break;
		}
	}

	private void getHomeListData(final int method) {
		if (method == Constant.REFRESH) {
			swipeRefreshLayout.setRefreshing(true);
			curPage = 1;
		}
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("curPage", curPage);
		jsonObject.addProperty("pageSize", pageSize);
		jsonObject.addProperty("programaId", 1);
		ZbHttpClient.postNewApi(ServerConfig.API_NEWS_LIST, jsonObject,
				new TypeGsonHttpHandler<SuperResult<News>>() {

					@Override
					public void onSuccess(SuperResult<News> data) {
						homeListData.clear();
						adapter.notifyDataSetChanged();
						if (method == Constant.REFRESH) {
							if (data.getData() != null) {
								if (data.getData().size() > 0) {
									homeListData.clear();
									homeListData.addAll(data.getData());
									adapter.notifyDataSetChanged();
								}
							}
						}
						swipeRefreshLayout.setRefreshing(false);
						indetermininate.setVisibility(View.GONE);
						error_layout.setVisibility(View.GONE);
						adapter.notifyDataSetChanged();
					}

					@Override
					public void onFailure(String errorCode, String errorMsg) {
						homeListData.clear();
						adapter.notifyDataSetChanged();
						swipeRefreshLayout.setRefreshing(false);
						error_layout.setVisibility(View.VISIBLE);
						indetermininate.setVisibility(View.GONE);
					}
				});

	}

	@Override
	protected void initData() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.INTENT_ACTION_CHANGE_CITY);
		context.registerReceiver(broadcastReceiver, filter);
	}

	private MyItemClickListener onItemClickListener = new MyItemClickListener() {

		@Override
		public void onitemClick(View view, int position) {
			if (position == homeListData.size() + 1) {
				UmengUtil.onEvent(context, Constant.UMENG_HOME_MORE);
				goActivity2(MainActivity.class, KeyUtil.GOTO_FRAGMENT, KeyUtil.FRAG_NEWS);
				// ((MainActivity)
				// getActivity()).changeFragment(KeyUtil.FRAG_NEWS);
			}
			// 跳转到资讯详情
			if (position <= 0 || position > homeListData.size()) {
				return;
			}
			position = position - 1;
			LogUtil.printD("demolog", position + "");
			DbManager.saveNewsRead(homeListData.get(position).getNewsId() + "");
			Constant.isShowStatic = true;
			Intent intent = new Intent(getActivity(), GameDataActivity.class);

			intent.putExtra("Url", homeListData.get(position).getNewsUrl());
			intent.putExtra("Title", "热点");
			intent.putExtra("ShowShare", true);
			if (homeListData.get(position).getNewsImg() != null
					&& homeListData.get(position).getNewsImg().size() > 0) {
				intent.putExtra("ImageUrl", homeListData.get(position).getNewsImg().get(0).getImgUrl());
			}
			intent.putExtra("ShareTitle", homeListData.get(position).getNewsTitle());
			intent.putExtra("SummaryTx", homeListData.get(position).getNewsModel());
			UmengUtil.onEvent(context, Constant.UMENG_HOME_NEWS);
			getActivity().startActivity(intent);

		}
	};
	/**
	 * 注册的广播
	 */
	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (Constant.INTENT_ACTION_CHANGE_CITY.equals(intent.getAction())) {
				homeListData.clear();
				indexFunBeans.clear();
				adapter.notifyDataSetChanged();
				gridViewAdapter.notifyDataSetChanged();
				getHomeListData(Constant.REFRESH);
				swipeRefreshLayout.setRefreshing(true);
			}
		}

	};


	protected void getProgarmList() {
		ZbHttpClient.postNewApi(ServerConfig.API_NEWS_PROGRAM_LIST, new JsonObject(),
				new TypeGsonHttpHandler<List<NewsProgarm>>() {
					@Override
					public void onSuccess(List<NewsProgarm> data) {
						if (data != null) {
							List<NewsProgarm> pList = data;
							App.newsList.clear();
							App.newsList.addAll(pList);
							DbManager.saveProgarmList(pList);
							LogUtil.printI(TAG, pList.toString());
						}
					}

					@Override
					public void onFailure(String errorCode, String errorMsg) {}
				});

	}

}
